package br.ucb.sigplan.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import br.ucb.sigplan.beans.Calendario;
import br.ucb.sigplan.crud.CalendarioCrud;
import br.ucb.sigplan.enuns.DiasSemanaEnum;

public class DataUtil {
	
	public static List<Calendar> getAulas(List<DiasSemanaEnum> dias, Calendar inicioSemestre, Calendar fimSemestre) {
		List<Calendar> aulas = new ArrayList<Calendar>();
		int dia, qtdeDias;
		for (int mes = inicioSemestre.get(Calendar.MONTH); mes <= fimSemestre.get(Calendar.MONTH); mes++) {
			dia = (mes == inicioSemestre.get(Calendar.MONTH) ? inicioSemestre.get(Calendar.DAY_OF_MONTH) : 1);
			qtdeDias = qtdeDiasMes(mes+1, inicioSemestre.get(Calendar.YEAR));
			while((dia <= qtdeDias) || (mes == fimSemestre.get(Calendar.MONTH) &&  dia < fimSemestre.get(Calendar.DATE))){
				for (DiasSemanaEnum diasSemanaEnum : dias) {
					addDia(aulas, getDia(dia, mes+1, inicioSemestre.get(Calendar.YEAR)),diasSemanaEnum);
				}
				dia++;
			}
		}
		return aulas;
	}
	
	public static void addDia(List<Calendar> aulas, Date data, DiasSemanaEnum monday) {
		if (isAula(data, monday)) {
			aulas.add(getDia(data));
		}
	}
	
	public static boolean isFeriado(Date data) {
		List<Calendario> feriados = CalendarioCrud.findDatas('F');
		for (Calendario calendario : feriados) {
			if (calendario.getData().getTime().equals(data)) {
				return true;
			}
		}
		return false;
	}
	
	public static Calendar getDia(Date dia) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(dia);
		return cal;
	}
	
	public static boolean isAula (Date data, DiasSemanaEnum monday){
		return getDia(data).get(Calendar.DAY_OF_WEEK) == monday.getValue(); 
	}
	
	public static int qtdeDiasMes (int mes, int ano){
		switch (mes) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		case 2:
			if (anoBisexto(ano))
				return 29;
			else
				return 28;
		}
		return 0;
	}
	
	public static boolean anoBisexto (int ano){
		if ((ano % 4) == 0)
			return true;
		return false;	
	}
		
	public static Date getDia (int dia, int mes, int ano){
		return new GregorianCalendar(ano, mes-1,dia).getTime();					 	
	}

	public static Calendar getDataFromString(String data) {
		Integer year = new Integer(data.substring(data.lastIndexOf("/")+1));
		Integer day  = new Integer(data.substring(data.indexOf("/")+1, data.lastIndexOf("/")));
		Integer month = new Integer(data.substring(0, data.indexOf("/")));
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month-1, day);
		
		return calendar;
	}
	
	public static Calendar getDataFromBanco(java.sql.Date data) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(data);
		return cal;
	}
	
}
